import 'package:encrypt/encrypt.dart';
import 'package:libflutter/net/RDOnError.dart';
import 'package:libflutter/net/bean/UserData.dart';
import 'package:libflutter/rd/RDNetInheritedWidget.dart';
import 'package:pointycastle/asymmetric/api.dart';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class LoginByPasswordWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _LoginByPasswordState();
  }
}

class _LoginByPasswordState extends State<LoginByPasswordWidget> {
  @override
  Widget build(BuildContext context) {
    var of = RDNetInheritedWidget.of(context)!;

    return Scaffold(
      body: Center(
          child: Column(
        children: [
          Spacer(),
          TextButton(
            onPressed: () async {
              print(" Login 1 ${of.api} ");
              var rsaKey = await of.api.getRSAKey();
              var account = "15034165204";
              var password = "a123456";
              var keyString =
                  "-----BEGIN PUBLIC KEY-----\n${rsaKey.data}\n-----END PUBLIC KEY-----";
              RSAPublicKey publicKey = RSAKeyParser().parse(keyString) as RSAPublicKey;
              final passwordEncrypted = Encrypter(RSA(publicKey: publicKey)).encrypt(password);
              var loginResponse = await of.api
                  .loginByPassword(account, passwordEncrypted.base64, rsaKey.data.toString());
              var userData = UserData.fromJson(loginResponse.data);
              print("Login ${userData.runtimeType} ${userData}");
              print("Login ${userData.userInfo.runtimeType} ${userData.userInfo}");
            },
            child: Text("登陆功能"),
          ),
          TextButton(
            onPressed: () {
              Stream.value(of.api.getRSAKey()).listen((event) {
                print(" Login 1 $event ");
              }).onError((error) {
                print(" Login 1 $error ");
              });
            },
            child: Text("测试RxDart"),
          ),
          TextButton(
            onPressed: () {
              of.api.getRSAKeyBy((data) {
                print(" Login 1 $data ");
              }, onError: createCallSuper(onError: (error , rdOnError) {
                print(" Login 1 $error ");
              }));
            },
            child: const Text("测试 回调 调用父异常处理"),
          ),
          TextButton(
            onPressed: () {
              of.api.getRSAKeyBy((data) {
                print(" Login 1 $data ");
              }, onError: createIgnoreSuper(onError: (error, rdOnError) {
                print(" Login 1 $error ");
              }));
            },
            child: const Text("测试 回调 忽略父异常处理"),
          ),
          Spacer(),
        ],
      )),
    );
  }
}
